package com.tensai.study.问题.未解决的问题.逃逸分析;

/**
 * @author Tensai
 */
public class JVM {
    public static void main(String[] args) throws Exception {
        int sum = 0;
        int count = 1000000;
        //warm up
        for (int i = 0; i < count ; i++) {
            sum += fn(i);
        }

        Thread.sleep(500);

        for (int i = 0; i < count ; i++) {
            sum += fn(i);
        }

        System.out.println(sum);
        System.in.read();
    }

    /**
     * User对象的作用域局限在方法fn中，
     * 可以使用标量替换的优化手段在栈上分配对象的成员变量，
     * 这样就不会生成User对象，大大减轻GC的压力
     * @param age
     * @return
     */
    private static int fn(int age) {
        User user = new User(age);
        int i = user.getAge();
        return i;
    }
}

class User {
    private final int age;

    public User(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}
